package com.edu.hre.struts.action.admin;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRole;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.UserUpdateForm;

public class UserUpdateAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(UserUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "userUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		UserUpdateForm beanForm = (UserUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm, true);
			return mapping.findForward(ACTION_NAME);
		}

		String message = validateInsertForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm, true);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Save or update.
		HreUser tmp = new HreUser();
		tmp.setUserRoleId(beanForm.getUserRoleId());
		tmp.setUserName(CommonUtils.normalizeString(beanForm.getUserName()));
		tmp.setEmpNumber(beanForm.getEmployeeNumber());
		tmp.setUserPassword(Encrypter.encodeMD5(beanForm.getPassword()));
		tmp.setDeleted(false);
		tmp.setStatus(CommonUtils.normalizeInteger(beanForm.getStatus()) == 1);
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);

		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm, true);
			return mapping.findForward("jobTitleUpdate");
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		UserUpdateForm beanForm = (UserUpdateForm) form;
		beanForm.setIsAddNew(false); 
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreUser tmp = baseService.getPojo(id, HreUser.class);
			
			if (tmp == null) {
				initFormBean(beanForm, true);
				beanForm.setMessage(StringConstants.BLANK);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setEmployeeNumber(tmp.getEmpNumber());
			beanForm.setUserRoleId(tmp.getUserRoleId());
			beanForm.setUserName(CommonUtils.normalizeString(tmp.getUserName()));
			beanForm.setStatus(tmp.isStatus() ? 1 : 0);
			
			HreUserRole tmpRole = baseService.getFirstPojo("id", Compare.EQUAL, tmp.getUserRoleId(), null, null, 0, HreUserRole.class);
			boolean assignable = true;
			if (tmpRole != null) {
				assignable = tmpRole.getIsAssignable();
			}

			initFormBean(beanForm, assignable);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreUserRole tmpRole = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getUserRoleId(), null, null, 0, HreUserRole.class);
		boolean assignable = true;
		if (tmpRole != null) {
			assignable = tmpRole.getIsAssignable();
		}
		
		String message = validateUpdateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm, assignable);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreUser tmp = baseService.getPojo(beanForm.getId(), HreUser.class);
		if (tmp == null) {
			initFormBean(beanForm, assignable);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}
		
		tmp.setId(beanForm.getId());
		tmp.setEmpNumber(beanForm.getEmployeeNumber());
		tmp.setUserName(CommonUtils.normalizeString(beanForm.getUserName()));
		if (!StringConstants.BLANK.equals(beanForm.getPassword())) {
			tmp.setUserPassword(Encrypter.encodeMD5(beanForm.getPassword()));
		}
		tmp.setUserRoleId(beanForm.getUserRoleId());
		tmp.setDeleted(false);
		tmp.setStatus(1 == CommonUtils.normalizeInteger(beanForm.getStatus()));
		tmp.setDateModified(new Date());
		
		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm, assignable);
			return mapping.findForward("jobTitleUpdate");
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}

	private void initFormBean(UserUpdateForm beanForm, boolean isAssignable) {

		beanForm.setAllStatuses(ComboBoxInit.getAllEnabledStatuses(false));
		beanForm.setAllUserRoles(ComboBoxInit.getAllUserRoles(isAssignable, false));
		beanForm.setAllEmployees(ComboBoxInit.getAllEmployees(false));
	}
	
	private String validateUpdateForm (UserUpdateForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getUserName()))){
			return "User name cannot be blank!";
		}
		
		String verifyUserName = CommonUtils.verifyUserName(CommonUtils.normalizeString(beanForm.getUserName()), false);
		if (!StringConstants.BLANK.equals(verifyUserName)) {
			return verifyUserName;
		}

		if(!StringConstants.BLANK.equals(beanForm.getPassword()) && !beanForm.getPassword().equals(beanForm.getConfirmPassword())){
			return "Confirm password does not match!";
		}

		if(!StringConstants.BLANK.equals(beanForm.getPassword())) {
			String verifyPassword = CommonUtils.verifyPassword(beanForm.getPassword());
			if (!StringConstants.BLANK.equals(verifyPassword)) {
				return verifyPassword;
			}
		}

		return StringConstants.BLANK;
	}
	
	private String validateInsertForm (UserUpdateForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getUserName()))){
			return "User name cannot be blank!";
		}

		String verifyUserName = CommonUtils.verifyUserName(CommonUtils.normalizeString(beanForm.getUserName()), true);
		if (!StringConstants.BLANK.equals(verifyUserName)) {
			return verifyUserName;
		}

		if(StringUtils.isBlank(beanForm.getPassword())){
			return "Password cannot be blank!";
		}
		
		if(!beanForm.getPassword().equals(beanForm.getConfirmPassword())){
			return "Confirm password does not match!";
		}
		
		String verifyPassword = CommonUtils.verifyPassword(beanForm.getPassword());
		if (!StringConstants.BLANK.equals(verifyPassword)) {
			return verifyPassword;
		}

		return StringConstants.BLANK;
	}
}
